package app.sceledroid.network;

import java.io.IOException;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import app.sceledroid.R;
import app.sceledroid.activity.LoginActivity;
import app.sceledroid.activity.MainActivity;
import app.sceledroid.activity.LoginActivity.LoginStatus;
import app.sceledroid.entity.Course;
import app.sceledroid.entity.User;
import app.sceledroid.services.SceleService;

/**
 * 
 * @author r1nlx0
 * 
 *         Authenticator class that can be used in auth user and also get course
 *         of authenticated user
 */
public class Authenticator extends AsyncTask<String, Integer, Void> {

	private Context context;
	private DefaultHttpClient client;
	private User user;
	private SceleService sceleService;
	private LoginActivity.LoginStatus stat;
	private ProgressDialog dialog;
	private AlertDialog alertDialog;
	
	// private ArrayList<Course> courseResults;

	public Authenticator(SceleService sceleService, User user, Context context,
			DefaultHttpClient client, LoginActivity.LoginStatus  stat, ProgressDialog dialog) {
		super();
		this.context = context;
		this.client = client;
		this.stat = stat;
		this.user = user;
		this.dialog = dialog;

		alertDialog = new AlertDialog.Builder(context).create();
		// this.courseResults = new ArrayList<Course>();
		this.sceleService = sceleService;

	}

	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		//super.onPostExecute(result);
		if(dialog.isShowing())
		dialog.dismiss();
		if(stat == LoginStatus.SUCCED) {
			Intent intent = new Intent(context, MainActivity.class);
			context.startActivity(intent);
			sceleService.setLogin(true);
		}
		else if(stat == LoginStatus.ERROR) {
			alertDialog.setTitle("Error");
			alertDialog.setMessage("Username and password mismatch!");
			alertDialog.setOnCancelListener(new OnCancelListener() {
				
				//@Override
				public void onCancel(DialogInterface arg0) {
					// TODO Auto-generated method stub
					alertDialog.dismiss();
				}
			});
			alertDialog.show();
			
		}
	}

	@Override
	protected void onPreExecute() {
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		System.out.println(values[0]);
	}

	@Override
	protected Void doInBackground(String... params) {
		// Looper.prepare();
		try {
			
			String URL = params[0];
			HttpPost request = new HttpPost(params[0]);
			List<NameValuePair> requestPair = new ArrayList<NameValuePair>();
			requestPair.add(new BasicNameValuePair("username", user
					.getUsername()));
			Log.v("username", user.getUsername());
			requestPair.add(new BasicNameValuePair("password", user
					.getPassword()));
			Log.v("password", user.getPassword());
			request.setEntity(new UrlEncodedFormEntity(requestPair, HTTP.UTF_8));
			HttpResponse response = client.execute(request);

			List<Cookie> cStore = client.getCookieStore().getCookies();

			for (Cookie c : cStore) {
				Log.v("Cookie", c.getName() + c.getValue());
			}
			
			InputStream stream = response.getEntity().getContent();
			Document doc = Jsoup.parse(stream, "UTF-8", URL);
			Elements elements = doc.select("span.error");

			for (Element el : elements) {
				if (el.text().contains("Invalid login")) {
					Log.v("span.error", el.text());

					stat = LoginStatus.ERROR;
					return null;
				}
			}

			stat = LoginStatus.SUCCED;
			
			Elements courseElements = doc
					.select(".coursetree .depth0  a:not(.coursetreecommand)");
			int ii = 0;
			int size = courseElements.size();
			for (Element link : courseElements) {
				publishProgress(new Integer((ii*100)/size));
 				String linkHref = link.attr("href");
				String linkText = link.text();
				if (!linkHref.equals("#") && !linkHref.equals("")) {
					Course course = new Course(linkText, linkHref);
					sceleService.addCourse(course);
				}
				ii++;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			Log.v("Authenticator", e.getMessage());
			// Toast.makeText(context, e.getMessage(),
			// Toast.LENGTH_LONG).show();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block

			Log.v("Authenticator", e.getMessage());
			// Toast.makeText(context, e.getMessage(),
			// Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			// TODO Auto-generated catch block

			Log.v("Authenticator", e.getMessage());
			// Toast.makeText(context, e.getMessage(),
			// Toast.LENGTH_LONG).show();
		}
		// Looper.loop();
		return null;
	}

}
